package com.xxjqr.rbac.auth;

import cn.hutool.core.collection.CollUtil;
import com.xxjqr.rbac.mapper.TbUserMapper;

import lombok.AllArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.List;
import java.util.StringJoiner;

/**
 * @描述 UserDetailsService 实现类
 * @码农 丁昌江
 * @日期 2021/3/10 17:56
 */
@Service
@AllArgsConstructor
public class MyUserDetailsService implements UserDetailsService {

    private final TbUserMapper userMapper;


    /**
     * @描述 通过用户名获取该用户信息
     * @码农 丁昌江
     * @日期 2021/5/26 14:15
     * @param username
     * @返回 org.springframework.security.core.userdetails.UserDetails
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        //从数据库中获取用户
        JwtUser jwtUser = userMapper.getUserAndRole(username);
        if (ObjectUtils.isEmpty(jwtUser)) {
            return null;
        }

        jwtUser.setAuthorities(roleList2GrantedAuthority(jwtUser.getRoleCodes()));
        return jwtUser;
    }


    /** 根据从数据库中读取的角色码转换成springsecurity的角色列表
     * @param roleList
     * @描述 roleList2GrantedAuthority
     * @码农 丁昌江
     * @日期 2021/5/26 14
     * @返回 java.util.List<org.springframework.security.core.GrantedAuthority>
     */
    private List<GrantedAuthority> roleList2GrantedAuthority(List<String> roleList) {
        //如果角色码为空，那么返回一个空的权限列表
        if (CollUtil.isEmpty(roleList)) {
            return AuthorityUtils.createAuthorityList();
        }
        //逗号分隔的角色码转换成security的角色列表
        StringJoiner sj = new StringJoiner(",");
        for (String role : roleList) {
            sj.add(role);
        }
        return AuthorityUtils.commaSeparatedStringToAuthorityList(sj.toString());
    }
}
